package com.example.mongodb1.service.impl;

import com.example.mongodb1.entity.Form;
import com.example.mongodb1.repository.FormRepository;
import com.example.mongodb1.service.FormService;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class FormServiceImpl implements FormService {
    @Autowired
    private FormRepository formRepository;

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Form saveForm(Form form) {
        Form result = formRepository.save(form);
        createFieldsDocument(form);
        return result;
    }

    @Override
    public Form getForm(String id) {
        Optional<Form> byId = formRepository.findById(id);
       return byId.orElse(null);
    }

    @Override
    public List<Form> getForms() {
        List<Form> all = formRepository.findAll();
        return all;
    }

    @Override
    public Map<String, Object> saveFormData(String id, Map<String, Object> data) {
        Form form = getForm(id);
        if (form == null){
            throw new RuntimeException("Form not found");
        }
        data.put("formid", id);
        mongoTemplate.save(data,id+"_form");
        return data;
        }

    public void createFieldsDocument(Form form) {
        String field_name = form.getId()+"_form";
        if(!mongoTemplate.collectionExists(field_name)){
            mongoTemplate.createCollection(field_name);
        }
    }
}
